package main.java.Fzy.Demo.MyThread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

//自定义拒绝策略
public class CustomSolutionHandler implements RejectedExecutionHandler {

    private int discardNumber = 5;
    private List<Runnable> discardList = new ArrayList<>();

    public CustomSolutionHandler(int discardNumber){
        this.discardNumber = discardNumber;
    }

    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {

        if(executor.getQueue().size()>discardNumber){
            //批量移除线程队列中的discardNumber个线程任务
            executor.getQueue().drainTo(discardList,discardNumber);
            //清空discardList列表
            discardList.clear();
            if(!executor.isShutdown()){
                //尝试提交当前任务
                executor.execute(r);
            }
        }
    }
}
